import React, { useCallback, useState } from 'react';
import { TypographyTitle } from '@/components/Typography';

import { SearchOutlined, ReloadOutlined, EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons';

import ScrollBarLayout from '@/components/ScrollBarLayout';

import cls from 'classnames';
import _ from 'lodash';

import '../../styles.less';
import { AutoComplete, Input, Empty, Tree, Spin, Popover } from 'antd';
import MyIcon from '@/components/MyIcon';
import { positionAPI } from '../../type';
import pageStyles from '@/common/pageLayout.less';

export const OrganizationTree: React.FC<positionAPI.IOrgTreeProps> = ({
  treeData,
  loading,
  selectedKeys,
  onTreeSelectChange,
  getTreeData,
  setDeptTreeNode, //保存组织部门点击的数据
}) => {
  const prefix = 'org-tree';
  const prefixPover = 'position-popover';
  // const prefixTitle = 'org-table';

  const [autoOption, setAutoOption] = useState<any[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(false);
  const [seachValueDep, setSeachValueDep] = useState<string>(''); //保存左侧部门树搜索的值

  /**
   * 是否显示 详情气泡
   */
  const [showPopoverID, setShowPopoverID] = useState<string>('');

  /**
   * 显示 隐藏 详情方法
   * @param openID  显示图标
   * @param closeID  闭合图标
   * @param showPopo  显示详情的 id
   * @param isOpen  true 显示     false 隐藏
   */
  const clickEyeDetail = (openID: string, closeID: string, showPopo: string, isOpen: boolean) => {
    const eleOpen = document.getElementById(openID);
    const eleClose = document.getElementById(closeID);
    if (eleOpen) {
      eleOpen.style.display = isOpen ? 'none' : 'inline-block';
    }
    if (eleClose) {
      eleClose.style.display = isOpen ? 'inline-block' : 'none';
    }
    setShowPopoverID(showPopo);
  };

  const loopArray = (array: any[]): Record<string, any>[] => {
    const tileArray: Record<string, any>[] = [];
    const loop = (data: any[]) => {
      data?.forEach((item) => {
        if (item?.children) {
          loop(item?.children);
        }
        tileArray.push(item);
      });
    };

    loop(array);

    return tileArray;
  };

  const onSearch = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const searchValue = e.target.value;
      setSeachValueDep(searchValue);
      const tileArray: Record<string, any>[] = loopArray(treeData);

      if (searchValue && searchValue.length > 0) {
        const newOption: any[] = tileArray
          ?.map((item) => {
            if (item?.name?.includes(searchValue)) {
              // const name = item?.name;
              // const nameLength = name?.length;
              // const select = name?.search(searchValue);
              // const searchLength = searchValue?.length;
              // const afterStr = name?.slice(0, select);
              // const selectStr = searchValue;
              // const beforeStr = name?.slice(select + searchLength, nameLength);

              return {
                value: item?.name,
                key: item?.id,
                // label: (
                //   <div>
                //     <span>{afterStr}</span>
                //     <span style={{ color: '#f50' }}>{selectStr}</span>
                //     <span>{beforeStr}</span>
                //   </div>
                // ),
              };
            }
          })
          ?.filter((item) => typeof item !== 'undefined');
        setAutoOption(newOption);
      } else {
        setAutoOption([]);
        getTreeData();
      }
    },
    [treeData, autoOption],
  );

  /**
   * 显示新增编辑按钮
   * @param id
   * @param flag
   * @returns
   */
  const onTreeNodeMouseEnter = (id: string, flag: boolean) => {
    const ele = document.getElementById(id);
    if (flag) {
      return;
    } else if (ele) {
      ele.style.display = 'block';
    }
  };

  /**
   * 隐藏新增编辑按钮
   * @param id
   * @param flag
   * @returns
   */
  const onTreeNodeMouseLeave = (id: string, flag: boolean) => {
    const ele = document.getElementById(id);
    if (flag) {
      return;
    } else if (ele) {
      ele.style.display = 'none';
    }
  };

  const orgTreeData = (data: any[]): any[] => {
    return data?.map((item) => {
      const idName = item?.id + 'ShowBtnOrganizaTreeType';
      const detailEyeShow = item?.id + 'eyeShow' + Math.random();
      const detailEyeHiddren = item?.id + 'eyeHiddren' + Math.random();
      const showpopoverDom = item?.id + 'showpopoverDom';
      const flag = false;

      const content = (
        <div style={{ color: '#000000D9' }}>
          <p>
            类别：
            <span style={{ color: item.deptTypeName?.split('||')[1] || '' }}>
              {(item.deptTypeName && item.deptTypeName?.split('||')[0]) || '--'}
            </span>
          </p>
          <p>简码：{item.shortCode}</p>
          <p>
            状态：
            {item.isOpen == 0 ? <span style={{ color: 'red' }}>禁用</span> : <span style={{ color: 'green' }}>启用</span>}
          </p>
        </div>
      );

      const name = item?.name;
      const nameLength = name?.length;
      const select = name?.search(seachValueDep);
      const searchLength = seachValueDep?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = seachValueDep;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <span className={pageStyles['over-flow-hidden']}>
            {afterStr}
            <span style={{ color: '#f50' }}>{selectStr}</span>
            {beforeStr}
          </span>
        ) : (
          <span className={pageStyles['over-flow-hidden']}>{item?.name}</span>
        );

      // if (item?.children) {
      return {
        ...item,
        title: (
          <Popover
            placement="bottomLeft"
            content={content}
            title={item.name}
            color={'rgb(222 222 222)'}
            destroyTooltipOnHide={{ keepParent: false }}
            overlayClassName={cls(prefixPover)}
            open={showpopoverDom == showPopoverID ? true : false}
          >
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                overflow: 'hidden',
              }}
              onMouseEnter={() => {
                onTreeNodeMouseEnter(idName, flag);
              }}
              onMouseLeave={() => {
                onTreeNodeMouseLeave(idName, flag);
                clickEyeDetail(detailEyeShow, detailEyeHiddren, '', false);
              }}
            >
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  // cursor: item?.category == 0 ? 'no-drop' : 'pointer',
                  width: '90%',
                  overflow: 'hidden',
                }}
                id={item?.id}
              >
                {getTreeIcon(String(item?.category))}
                {titleTree}
              </div>
              <div
                id={idName}
                style={{
                  whiteSpace: 'nowrap',
                  display: flag ? 'block' : 'none',
                }}
              >
                <a
                  style={{
                    display: 'inline-block',
                    marginRight: 8,
                  }}
                  id={detailEyeShow}
                  onClick={(e) => {
                    e?.stopPropagation();
                    clickEyeDetail(detailEyeShow, detailEyeHiddren, showpopoverDom, true);
                  }}
                >
                  <EyeOutlined />
                </a>
                <a
                  id={detailEyeHiddren}
                  style={{
                    display: 'none',
                    marginRight: 8,
                  }}
                  onClick={(e) => {
                    e?.stopPropagation();
                    clickEyeDetail(detailEyeShow, detailEyeHiddren, '', false);
                  }}
                >
                  <EyeInvisibleOutlined />
                </a>
              </div>
            </div>
          </Popover>
        ),
        key: item?.id,
        children: item?.children?.length > 0 ? orgTreeData(item?.children) : null,
        // selectable: item?.category == 0 ? false : true,
      };
      // }
      // return {
      //   ...item,
      //   title: (
      //     <Popover
      //       placement="bottomLeft"
      //       content={content}
      //       trigger={'hover'}
      //       title={item.name}
      //       color={'rgb(222 222 222)'}
      //       overlayClassName={cls(prefixPover)}
      //       style={{ maxWidth: '15%' }}
      //     >
      //       <div
      //         style={{
      //           display: 'flex',
      //           alignItems: 'center',
      //           paddingRight: 20,
      //           cursor: item?.category == 0 ? 'no-drop' : 'pointer',
      //         }}
      //         id={item?.id}
      //       >
      //         {getTreeIcon(String(item?.category))}
      //         {titleTree}
      //       </div>
      //     </Popover>
      //   ),
      //   key: item?.id,
      //   selectable: item?.category == 0 ? false : true,
      // };
    });
  };

  const getTreeIcon = (category: string) => {
    switch (category) {
      case '0':
        return <MyIcon style={{ marginRight: 5 }} type="icon-bank" />;
      case '1':
        return <MyIcon style={{ marginRight: 5 }} type="icon-cluster" />;
      default:
        return <MyIcon style={{ marginRight: 5 }} type="icon-icon_lingdaopishi" />;
    }
  };

  const onAutoSelect = useCallback(
    (value: string, option: any) => {
      setSeachValueDep(value);
      setAutoExpandParent(true);
      const optionId = option?.key;
      const targetNode = loopArray(treeData)?.find((i) => i?.id == optionId);
      onTreeSelectChange(optionId);
      setExpandedKeys([targetNode?.pID]);

      // 滚动定位
      setTimeout(() => {
        scrollToAnchor(optionId);
      }, 1000);
    },
    [expandedKeys, treeData],
  );

  const onTreeSelect = useCallback(
    (e: any, node: any) => {
      const [id] = e;
      onTreeSelectChange(id);
      setDeptTreeNode(node?.node);
    },
    [selectedKeys],
  );

  const onTreeExpand = useCallback(
    (e: any) => {
      setExpandedKeys(e);
      setAutoExpandParent(false);
    },
    [expandedKeys],
  );

  // 滚动定位
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id);
    if (id) {
      anchorElement?.scrollIntoView({ block: 'start', behavior: 'smooth' });
    }
  };

  return (
    <div className={cls(prefix)}>
      {/* <div className={cls(prefixTitle + '-head')}>
        <div className={cls(prefixTitle + '-title')}>
          <TypographyTitle
            level={4}
            style={{
              margin: 0,
            }}
          >
            组织机构
          </TypographyTitle>
        </div>
        <div className={cls(prefixTitle + '-opt')}>
          <Button
            icon={<ReloadOutlined />}
            onClick={getTreeData}
            onMouseOut={(event: any) => {
              event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
            }}
          >
            重置
          </Button>
        </div>
      </div> */}
      <div className={cls(prefix + '-title')}>
        <TypographyTitle
          level={4}
          style={{
            margin: 0,
          }}
        >
          组织机构
        </TypographyTitle>
      </div>
      <div className={cls(prefix + '-body')}>
        <div className={cls(prefix + '-body-search')}>
          <AutoComplete
            style={{ width: '100%' }}
            options={autoOption}
            notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
            onSelect={onAutoSelect}
          >
            <Input
              suffix={<SearchOutlined />}
              onChange={onSearch}
              placeholder="按机构名称搜索"
              allowClear={true}
              addonAfter={
                <ReloadOutlined
                  onClick={(event: any) => {
                    event.stopPropagation();
                    getTreeData();
                  }}
                />
              }
            />
          </AutoComplete>
        </div>
        <div className={cls(prefix + '-body-content')}>
          <ScrollBarLayout style={{ padding: '0rem 1rem' }}>
            <Spin spinning={loading} style={{ marginTop: 20 }}>
              {treeData && treeData?.length > 0 ? (
                <Tree
                  treeData={orgTreeData(treeData)}
                  blockNode={true}
                  autoExpandParent={autoExpandParent}
                  onSelect={onTreeSelect}
                  selectedKeys={selectedKeys}
                  expandedKeys={expandedKeys}
                  onExpand={onTreeExpand}
                />
              ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
              )}
            </Spin>
          </ScrollBarLayout>
        </div>
      </div>
    </div>
  );
};
